package com.raychi.demo.servlet.product;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.raychi.demo.util.JdbcUtil;

public class ProductSaveServlet extends HttpServlet{

	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		req.getRequestDispatcher("/product/inputProduct.jsp").forward(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		try{
			req.setCharacterEncoding("utf-8");
			String name = req.getParameter("name");
			int price = Integer.valueOf(req.getParameter("price"));
			saveProduct2DB(name, price);
			resp.sendRedirect(req.getContextPath()+"/product/");
		}catch(Exception e){
			e.printStackTrace();
		}
	}

	private void saveProduct2DB(String name, int price) throws SQLException,
			ClassNotFoundException {
		Connection conn = JdbcUtil.getConnection();
		String sql = "insert into product (name,price) values (?,?)";
		PreparedStatement ps = conn.prepareStatement(sql);
		ps.setString(1, name);
		ps.setInt(2, price);
		ps.execute();
		conn.commit();
	}
	
}
